package com.cby.android.sample.fragments

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import androidx.appcompat.widget.Toolbar
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.bingoogolapple.bgabanner.BGABanner
import com.cby.android.library.base.BaseStateFragment
import com.cby.android.library.ext.getColor
import com.cby.android.library.ext.observe
import com.cby.android.library.ext.showToast
import com.cby.android.library.ext.start
import com.cby.android.library.mvi.ApiError
import com.cby.android.sample.MainActivity
import com.cby.android.sample.R
import com.cby.android.sample.activities.RollMoreActivity
import com.cby.android.sample.adapter.BannerAdapter
import com.cby.android.sample.adapter.HomeArticleAdapter
import com.cby.android.sample.constant.Constant.KEY_LOCATION
import com.cby.android.sample.ext.openWeather
import com.cby.android.sample.intent.HomeIntent
import com.cby.android.sample.model.HomeViewModel
import com.cby.android.sample.state.HomeState
import com.cby.android.sample.utils.CaiyunUtils
import com.cby.android.sample.utils.WeatherUtils
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener
import com.scwang.smart.refresh.layout.listener.OnRefreshListener
import kotlinx.coroutines.launch

/**
 * @description: HomeFragment
 * @author: ChenBaoYang
 * @createDate: 2022/4/29 2:45 下午
 */
class HomeFragment : BaseStateFragment<HomeViewModel, HomeState, HomeIntent>(), OnLoadMoreListener,
    OnRefreshListener {

    private val toolbar: Toolbar? by lazy { findViewById(R.id.toolbar) }
    private val recyclerView: RecyclerView? by lazy { findViewById(R.id.recycler_view) }
    private val refreshLayout: RefreshLayout? by lazy { findViewById(R.id.refreshLayout) }
    private lateinit var banner: BGABanner

    private lateinit var location: String

    private var weatherCode: String? = null
    private var menuItem: MenuItem? = null

    private lateinit var homeArticleAdapter: HomeArticleAdapter
    private lateinit var bannerAdapter: BannerAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setHasOptionsMenu(true)//加上这句话，menu才会显示出来
    }

    override fun parseArgs() {
        location = arguments?.get(KEY_LOCATION) as String
    }

    override fun getLayoutId() = R.layout.fragment_home

    override fun onViewInit(view: View) {
        toolbar?.run {
            setBackgroundColor(getColor(R.color.colorAccent))
            title = "首页"
            navigationIcon = null
            inflateMenu(R.menu.home_menu)
            menuItem = menu.findItem(R.id.home_weather)
            setOnMenuItemClickListener {
                when (it.itemId) {
                    R.id.home_search -> start(RollMoreActivity::class.java)
                    R.id.home_weather -> (activity as MainActivity).openWeather()
                }
                true
            }
        }


        //获取banner页面，并赋值,设置监听
        val view = LayoutInflater.from(activity).inflate(R.layout.include_banner, null)

        homeArticleAdapter = HomeArticleAdapter(R.layout.item_article)
        bannerAdapter = BannerAdapter(requireActivity())
        banner = view.findViewById(R.id.banner)
        banner.setAdapter(bannerAdapter)
        banner.setDelegate { banner, itemView, model, position -> showToast("当前功能，开发中......") }

        homeArticleAdapter.addHeaderView(view)


        recyclerView?.apply {
            layoutManager = LinearLayoutManager(context)
            setHasFixedSize(true)
            adapter = homeArticleAdapter
        }

        refreshLayout?.setOnLoadMoreListener(this)
        refreshLayout?.setOnRefreshListener(this)
    }

    override fun loadData() {
        reload()
    }

    override fun bindLiveData() {
        observe(viewModel!!.state){

            refreshLayout?.finishLoadMore(true)
            refreshLayout?.finishRefresh(true)

            if (!TextUtils.isEmpty(it.errorMsg)) {
                showToast(it.errorMsg!!)
                return@observe
            }

            if (it.page > 0) {
                homeArticleAdapter.addData(it.wanArticles)
            } else {
                homeArticleAdapter.setNewInstance(it.wanArticles)
                banner.setData(it.wanBanners, null)

                weatherCode = CaiyunUtils.getWeatherText(it.dataCaiYunWeather?.skycon)
                menuItem?.setIcon(WeatherUtils.getWeatherResId(weatherCode))
            }

        }
    }

    override fun reload() {
        lifecycleScope.launch {
            viewModel?.intents?.send(HomeIntent.LoadDataIntent(location))
        }
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        lifecycleScope.launch {
            viewModel?.intents?.send(HomeIntent.LoadMoreDataIntent)
        }
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        reload()
    }

    override fun getPageTarget(): Any {
        return refreshLayout!!
    }
}